package com.lxmes.sales.service.impl;

import java.util.Date;
import java.util.List;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.bean.BeanUtils;
import com.lxmes.sales.domain.AssetKucun;
import com.lxmes.sales.domain.AssetRuku;
import com.lxmes.sales.domain.Assetfiles;
import com.lxmes.sales.mapper.AssetKucunMapper;
import com.lxmes.sales.mapper.AssetfilesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.lxmes.sales.mapper.AssetChukuMapper;
import com.lxmes.sales.domain.AssetChuku;
import com.lxmes.sales.service.IAssetChukuService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资产出库Service业务层处理
 *
 * @author cdc
 * @date 2024-08-14
 */
@Service
public class AssetChukuServiceImpl implements IAssetChukuService
{
    @Autowired
    private AssetChukuMapper assetChukuMapper;
    @Autowired
    private AssetKucunMapper assetKucunMapper;
    @Autowired
    private AssetfilesMapper assetfilesMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询资产出库
     *
     * @param id 资产出库主键
     * @return 资产出库
     */
    @Override
    public AssetChuku selectAssetChukuById(Long id)
    {
        return assetChukuMapper.selectAssetChukuById(id);
    }

    /**
     * 查询资产出库列表
     *
     * @param assetChuku 资产出库
     * @return 资产出库
     */
    @Override
    public List<AssetChuku> selectAssetChukuList(AssetChuku assetChuku)
    {
        return assetChukuMapper.selectAssetChukuList(assetChuku);
    }

    /**
     * 新增资产出库
     *
     * @param assetChuku 资产出库
     * @return 结果
     */
    @Override
    public int insertAssetChuku(AssetChuku assetChuku)
    {
        String danhao= "CKZC"+ NewNumber.createNewNumber(assetChukuMapper.getNewCode(DateUtils.getDate()));
        List<AssetChuku> list = assetChuku.getInfoList();
        if(list.size()>0){
            for ( AssetChuku info:list) {
                info.setId(null);
                info.setDanhao(danhao);
                info.setDeptId(assetChuku.getDeptId());
                info.setDeptName(assetChuku.getDeptName());
                info.setOrgCode(SecurityUtils.getFactoryCode());
                info.setOrgName(SecurityUtils.getFactoryName());
                info.setChukuType(assetChuku.getChukuType());
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                assetChukuMapper.insertAssetChuku(info);
            }
        }else {
            throw new ServiceException("资产出库明细不存在！");
        }
        return 1;
    }

    /**
     * 修改资产出库
     *
     * @param assetChuku 资产出库
     * @return 结果
     */
    @Override
    public int updateAssetChuku(AssetChuku assetChuku)
    {
        return assetChukuMapper.updateAssetChuku(assetChuku);
    }

    @Override
    @Transactional
    public int shAssetChuku(AssetChuku assetChuku) {
        List<Long> idsList = assetChuku.getIds();
        for (Long id:idsList) {
            AssetChuku ck = assetChukuMapper.selectAssetChukuById(id);
            if(ck.getShStatus().equals("1")){
                throw new ServiceException("资产出库库单【"+ck.getAssetCode()+"】已审核，不能重复审核！");
            }
            ck.setShStatus("1");
            ck.setShName(SecurityUtils.getUsername());
            ck.setShDate(DateUtils.getNowDate());
            assetChukuMapper.updateAssetChuku(ck);
            this.syncStock(ck);
            //创建资产档案
            if("202".equals(ck.getChukuType())){
               this.createAssetfiles(ck);
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int qxshAssetChuku(AssetChuku assetChuku) {
        List<Long> idsList = assetChuku.getIds();
        for (Long id:idsList) {
            AssetChuku ck = assetChukuMapper.selectAssetChukuById(id);
            if(ck.getShStatus().equals("0")){
                throw new ServiceException("资产出库单【"+ck.getAssetCode()+"】未审核，不能取消审核！");
            }
            ck.setShStatus("0");
            ck.setShName("");
            ck.setShDate(DateUtils.getNowDate());
            assetChukuMapper.updateAssetChuku(ck);
            this.qxSyncStock(ck);
            //创建资产档案
            if("202".equals(ck.getChukuType())){
                this.qxAssetfiles(ck);
            }
        }
        return 1;
    }
    //同步库存
    public void  syncStock(AssetChuku assetChuku){
        AssetKucun queryKucun = new AssetKucun();
        queryKucun.setOrgCode(SecurityUtils.getFactoryCode());
        queryKucun.setBarcode(assetChuku.getBarcode());
        AssetKucun kucun = assetKucunMapper.selectAssetKucunByObj(queryKucun);
        if(kucun!=null){
            if(kucun.getKcNum().compareTo(assetChuku.getChukuNum())<0){
                throw new ServiceException("资产代码【"+assetChuku.getAssetCode()+"】库存不足，审核失败！");
            }
            kucun.setKcNum(kucun.getKcNum().subtract(assetChuku.getChukuNum()));
            kucun.setAmount(kucun.getKcNum().multiply(kucun.getUnitPrice()));
            assetKucunMapper.updateAssetKucun(kucun);
        }
    }
    //取消审核同步库存
    public void  qxSyncStock(AssetChuku assetChuku){
        AssetKucun queryKucun = new AssetKucun();
        queryKucun.setOrgCode(SecurityUtils.getFactoryCode());
        queryKucun.setBarcode(assetChuku.getBarcode());
        AssetKucun kucun = assetKucunMapper.selectAssetKucunByObj(queryKucun);
        if(kucun==null){
            throw new ServiceException("资产代码【"+assetChuku.getAssetCode()+"】未找到相应的库存信息！");
        }
        kucun.setKcNum(kucun.getKcNum().add(assetChuku.getChukuNum()));
        kucun.setAmount(kucun.getKcNum().multiply(kucun.getUnitPrice()));
        assetKucunMapper.updateAssetKucun(kucun);
        //撤销资产档案
        Assetfiles assetFilesQuery = new Assetfiles();
        assetFilesQuery.setAssetCode(assetChuku.getAssetCode());
        assetFilesQuery.setDanhao(assetChuku.getDanhao());
        List<Assetfiles> list = assetfilesMapper.selectAssetfilesList(assetFilesQuery);
        for (Assetfiles assetfile : list){
            assetfilesMapper.deleteAssetfilesById(assetfile.getId());
        }
    }
    //创建资产档案
    public void  createAssetfiles(AssetChuku assetChuku){
        int ckNum = assetChuku.getChukuNum().intValue();
        for (int i = 0; i < ckNum ; i++) {
            Assetfiles assetFiles = new Assetfiles();
            String number=assetChuku.getAssetCode()+ NewNumber.createNewNumber3(assetfilesMapper.get3NewCode(assetChuku.getAssetCode()));
            BeanUtils.copyBeanProp(assetFiles,assetChuku);
            assetFiles.setId(null);
            assetFiles.setBarcode(number);
            assetFiles.setPurchaseAmount(assetChuku.getUnitPrice());
            assetFiles.setSapProof(assetChuku.getDeptName());
            assetFiles.setReceivingUnit(assetChuku.getDeptId());
            assetFiles.setUssage("1");
            assetFiles.setAssetPosition("");
            assetFiles.setOperator("");
            assetFiles.setActivationTime(DateUtils.getNowDate());
            assetFiles.setDanhao(assetChuku.getDanhao());
            assetFiles.setCreateBy(SecurityUtils.getUsername());
            assetFiles.setCreateTime(DateUtils.getNowDate());
            assetFiles.setFree2("1");
            assetFiles.setFree5(assetChuku.getUnit());
            assetfilesMapper.insertAssetfiles(assetFiles);
        }
    }
    public void  qxAssetfiles(AssetChuku assetChuku){

        assetfilesMapper.deleteAssetfilesByDanhaoAndBarcode(assetChuku.getDanhao(),assetChuku.getBarcode());
    }
    /**
     * 批量删除资产出库
     *
     * @param ids 需要删除的资产出库主键
     * @return 结果
     */
    @Override
    public int deleteAssetChukuByIds(Long[] ids)
    {
        for (int i = 0; i <ids.length ; i++) {
            AssetChuku assetChuku = assetChukuMapper.selectAssetChukuById(ids[i]);
            if (assetChuku.getShStatus().equals("1")) {
                throw new ServiceException("资产出库单【" + assetChuku.getAssetCode() + "】已审核，先取消审核再删除！");
            }
        }
        return assetChukuMapper.deleteAssetChukuByIds(ids);
    }

    /**
     * 删除资产出库信息
     *
     * @param id 资产出库主键
     * @return 结果
     */
    @Override
    public int deleteAssetChukuById(Long id)
    {
        return assetChukuMapper.deleteAssetChukuById(id);
    }
    @Override
    public String imporIteminfo(List<AssetChuku> assetChukuList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(assetChukuList) || assetChukuList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AssetChuku assetChuku : assetChukuList)
        {
            try
            {
                BeanValidators.validateWithException(validator, assetChuku);
                assetChuku.setCreateBy(operName);
                assetChuku.setUpdateBy(operName);
                this.insertAssetChuku(assetChuku);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
